<?php
declare(strict_types=1);
/**
 * This file is part of EasySwoole.
 *
 * @link     https://www.easyswoole.com
 * @document https://www.easyswoole.com
 * @contact  https://www.easyswoole.com/Preface/contact.html
 * @license  https://github.com/easy-swoole/easyswoole/blob/3.x/LICENSE
 */

namespace App\Service\Auth;

use App\Dao\SysUserDao;
use App\Exception\Api\BadRequestException;
use App\Model\SysUserModel;
use App\Service\BaseService;
use App\Service\Captcha\CaptchaService;
use App\Service\SysUserService;
use App\Utility\Jwt\JwtUtil;
use App\Utility\Rsa\RsaUtils;

class AuthService extends BaseService
{
    public function getCode()
    {
        /** @var CaptchaService $captchaService */
        $captchaService = container()->make(CaptchaService::class);
        $result         = $captchaService->createCaptchaCode();
        return success($result);
    }

    public function login(array $post)
    {
        $username = $post['username'];
        $password = $post['password'];
        $code     = $post['code'];
        $uuid     = $post['uuid'];

        try {
            // 密码解密
            $privateKey    = config('app.rsa.private_key');
            $plainPassword = RsaUtils::decryptByPrivateKey($privateKey, $password);
            if (!$plainPassword) {
                throw new BadRequestException("验证码不存在或已过期");
            }

            // 检验验证码
            /** @var CaptchaService $captchaService */
            $captchaService = container()->make(CaptchaService::class);
            $captchaService->checkCaptchaCode($uuid, $code);

            // 校验用户名或密码
            /** @var SysUserDao $userDaoObj */
            $sysUserService = container()->make(SysUserService::class);
            /** @var SysUserModel $userDao */
            $userDao = $sysUserService->findByUsername($username);
            if (!$userDao) {
                throw new BadRequestException("用户名或密码错误");
            }
            if (!password_verify($plainPassword, $userDao->password)) {
                throw new BadRequestException("用户名或密码错误");
            }

            $token      = JwtUtil::createToken($username);
            $user       = $userDao->toArray(false, false);
            $user['id'] = $user['user_id'];
            unset($user['user_id']);
            $user          = convert_array($user);

            // todo::
            $user['dept']  = [
                'hasChildren' => false,
                'id'          => 2,
                'label'       => '研发部',
                'leaf'        => true,
                'name'        => '研发部',
                'subCount'    => 0,
            ];
            $user['jobs']  = [];
            $user['roles'] = [];

            // 返回 token 与 用户信息
            $authInfo = [
                'user'  => [
                    'authorities' => [['authority' => 'admin']],
                    'dataScopes'  => [],
                    'roles'       => ['admin'],
                    'user'        => $user
                ],
                'token' => $token,
            ];
        } catch (BadRequestException $exception) {
            return fail($exception->getMessage());
        }

        return success($authInfo);
    }
}
